package respository

import (
	"fmt"
	"gitee.com/song-yao-shun/MQH/common"
	"gitee.com/song-yao-shun/MQH/model"
	"gorm.io/gorm"
	"log"
)

//定义接口和定义增删改查的方法
type IPostRepository interface {
	Create(post model.Post)
	Update(post model.Post)
	SelectById(Id int)
	DeleteById(Id int)
	List(pageNum int, pageSize int)
}

type PostRepository struct {
	DB *gorm.DB
}

func (p PostRepository) Create(post model.Post) (string, error){

	if err := p.DB.Preload("Category").Create(&post).Error; err != nil {
		log.Printf("新增失败，错误信息为：%v",err)
		return "", err
	}

	return fmt.Sprint(post.ID), nil
}

func (p PostRepository) Update(post model.Post) (*model.Post, error){

	if err := p.DB.Updates(&post).Error;err != nil {
		return nil, err
	}
	//if err := p.DB.Model(&post).Updates(requestPost).Error;err != nil {
	//	return nil, err
	//}

	return &post,nil
}

func (p PostRepository) SelectById(Id string) (*model.Post, error){
	var post model.Post

	if err := p.DB.Preload("Category").Where("id=?",Id).First(&post).Error; err != nil{
		return nil, err
	}

	return &post, nil
}

func (p PostRepository) DeleteById(Id string) (rowsAffected int64) {
	//rowsAffected = p.DB.Delete(&post).RowsAffected
	rowsAffected = p.DB.Where("id = ?", Id).Delete(model.Post{}).RowsAffected
	if rowsAffected != 1 {
		log.Printf("数据删除失败，删除操作影响行数为：%v，删除的id为：%v",rowsAffected,Id)
	}

	return rowsAffected
}

func (p PostRepository) List(pageNum int, pageSize int) (posts []model.Post, total int64){
	p.DB.Preload("Category").Order("created_at desc").Offset((pageNum -1) * pageSize).Limit(pageSize).Find(&posts)

	// 前端渲染分页需要知道的总数
	p.DB.Model(model.Post{}).Count(&total)

	return posts,total
}

func NewPostRepository() PostRepository {
	db := common.GetDB()
	//db.AutoMigrate(model.Post{})

	return PostRepository{DB:db}
}
